package kr.co.chat.util;

import java.util.ArrayList;
import java.util.Calendar;

import kr.co.chat.util.ChatMessage;

public class ChatDB
{
	private static ChatDB chatdb = null;
	private ArrayList msgList = new ArrayList();
	private int msgIndex = 0;
	
	private ChatDB()
	{

	}
	
	public static ChatDB getInstance()
	{
		if(chatdb == null)
		{
			chatdb = new ChatDB();
		}
		
		return chatdb;
	}
	
	public int msgListSize()
	{
		return ChatDB.getInstance().msgList.size();
	}
	
	public synchronized boolean addMsg(ChatMessage chatMsg)
	{
		msgIndex++;
		chatMsg.setMessageID(msgIndex);
		
		return ChatDB.getInstance().msgList.add(chatMsg);
	}
	
	public synchronized ArrayList getMessage(int lastMsgID)
	{
		ArrayList msgList = new ArrayList();
		ArrayList removeMsg = new ArrayList();
		
		ChatMessage chatMsg = null;
		
		Calendar cal = Calendar.getInstance();
		
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), (cal.get(Calendar.SECOND) - 5));

		for(int i = 0; i < ChatDB.getInstance().msgList.size(); i++)
		{
			
			chatMsg = (ChatMessage)ChatDB.getInstance().msgList.get(i);
			
			if(chatMsg.getRegisterDate().getTime() <= cal.getTime().getTime())
			{
				removeMsg.add(String.valueOf(i));
			}
			
			if(chatMsg.getMessageID() > lastMsgID)
			{				
				msgList.add(chatMsg);
			}
		}
		
		for(int i = 0; i < removeMsg.size(); i++)
		{
			ChatDB.getInstance().msgList.remove(Integer.parseInt(removeMsg.get(i).toString()));
		}
		
		removeMsg.clear();
		removeMsg = null;
		
		return msgList;
	}
	
	public synchronized ChatMessage getLastMessage()
	{
		return (ChatMessage)ChatDB.getInstance().msgList.get(ChatDB.getInstance().msgList.size() - 1);
	}
}













